package database.access.layer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import domain.User;

public class UserDal {
	protected ConnectionManager mgr = null;
	protected Connection con = null;
	
	public UserDal(){
	}
	
	public void saveUser(User user) throws Exception{
		this.mgr = ConnectionManager.getInstance();
		this.con = mgr.getConnection();
		Statement st = con.createStatement() ;
		st.executeUpdate("insert into USER ( NAME, SURNAME, EMAIL, PASSWORD)" +
				"values ('" + user.getName() + "', '"+ user.getSurname()+"', '" +user.getEmail() + "' , '" +user.getPassword() + "')");
		st.close();
		mgr.closeConnection(con);
	}
	
	public User getUser(String email, String password) throws SQLException{
		this.mgr = ConnectionManager.getInstance();
		this.con = mgr.getConnection();
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery("select * from USER where email = '"+email+"' and password = '"+password+"'");
		rs.next();
		User user = new User(rs.getString(2), rs.getString(3), rs.getInt(1), rs.getString(4), rs.getString(5));
		rs.close();
		st.close();
		mgr.closeConnection(con);
		return user;
		
	}
	
	public ArrayList<String> getLastedRatedMovies(int userid) throws SQLException
	{
		ArrayList<String> movieNameList = new ArrayList<String>();
		
		this.mgr = ConnectionManager.getInstance();
		this.con = mgr.getConnection();
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery("Select m.name from MOVIE m, PREFERENCE p  where p.movieid = m.movieid and p.userid='"+userid+"' ");
		while(rs.next())
		{
			movieNameList.add(rs.getString(1));
			
		}		
		rs.close();
		st.close();
		mgr.closeConnection(con);
		return movieNameList;	
		
	}

}
